<?php
/**
 * @package Autogenerator for Joomla!
 * @version 3.0.0
 * @author Truong Cong Duc <truongcongduc4@gmail.com>
 * @link autogenerator.blogspot.com
 * @copyright (c) 2013, Truong Cong Duc
 * @license GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

class AutogeneratorModelXml_types extends JModelList
{

    public function __construct($config = array())
    {
        if (empty($config['filter_fields']))
        {
            $config['filter_fields'] = array(
                'id', 'axt.id',
                'title', 'axt.title',
                'description', 'axt.description',
                'type', 'axt.type',
                'xml_type_id', 'at.xml_type_id',
                'ordering', 'axt.ordering'
            );
        }

        parent::__construct($config);
    }

    protected function populateState($ordering = null, $direction = null)
    {
        $app = JFactory::getApplication();

        $search = $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search');

        $this->setState('filter.search', $search);

        $iLibId = $this->getUserStateFromRequest($this->context . '.filter.lib_id', 'filter_lib_id');
        
        $this->setState('filter.lib_id', $iLibId);
        
        parent::populateState('axt.title', 'asc');
    }

    protected function getStoreId($id = '')
    {
        // Compile the store id.
        $id .= ':' . $this->getState('filter.search');

        return parent::getStoreId($id);
    }

    public function getItems()
    {
        return parent::getItems();
    }

    protected function getListQuery()
    {
        $db = $this->getDbo();
        
        $query = $db->getQuery(true);

        $query->select($this->getState('list.select', 'axt.id, axt.title, axt.description, axt.type, axt.ordering'));
        
        $query->from('#__auto_xml_type AS axt');

        // For search.
        $search = $this->getState('filter.search');
        if (!empty($search))
        {
            if (stripos($search, 'id:') === 0)
            {
                $query->where('axt.id = ' . (int) substr($search, 3));
            }
            else
            {
                $search = $db->Quote('%' . $db->escape($search, true) . '%');
                $query->where('(axt.title LIKE ' . $search . ' OR axt.description LIKE ' . $search . ')');
            }
        }
        
        $iLibId = $this->getState('filter.lib_id');
        if (is_numeric($iLibId) && $iLibId > 0)
        {
            $query->where('axt.lib_id = ' . (int) $iLibId);
        }

        // For ordering.
        $orderCol = $this->state->get('list.ordering', 'axt.title');
        $orderDirn = $this->state->get('list.direction', 'asc');
        
        $query->order($db->escape($orderCol . ' ' . $orderDirn));

        return $query;
    }

}
